<!doctype html>
<html>
  <head>
    <title>PGlite PL/PGSQL Example</title>
    <link rel="stylesheet" href="./styles.css" />
    <script src="./utils.js"></script>
    <script type="importmap">
      {
        "imports": {
          "@electric-sql/pglite": "../dist/index.js"
        }
      }
    </script>
  </head>
<body>
<h1>PGlite <code>PL/PGSQL</code> Example</h1>
<div class="script-plus-log">
<script type="module">
import { PGlite } from "@electric-sql/pglite";

console.log("Starting...");
const pg = new PGlite();

let ret = await pg.exec(`
  CREATE EXTENSION IF NOT EXISTS plpgsql;
`);
console.log(ret);

await pg.exec(`
  CREATE OR REPLACE FUNCTION calculate_factorial(n INT) RETURNS INT AS $$
  DECLARE
      result INT := 1;
  BEGIN
      IF n < 0 THEN
          RAISE EXCEPTION 'The input cannot be negative.';
      ELSIF n = 0 OR n = 1 THEN
          RETURN result;
      ELSE
          FOR i IN 2..n LOOP
              result := result * i;
          END LOOP;
          RETURN result;
      END IF;
  END;
  $$ LANGUAGE plpgsql;
`);

ret = await pg.exec(`
  SELECT calculate_factorial(5) AS result;
`);
console.log(ret);
</script>
<div id="log"></div>
</div>
</body>
</html>
